package org.ym.tools.adapter;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.internal.$Gson$Types;
import com.google.gson.internal.ConstructorConstructor;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashMap;

/**
 * 自定义集合工厂创建对象
 * @author ym
 */
public class SelfCollectionTypeAdapterFactory implements TypeAdapterFactory {

    private final ConstructorConstructor constructorConstructor = new ConstructorConstructor(new HashMap(),true);
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
        if(Collection.class.isAssignableFrom(type.getRawType())){
            //获取此集合内的元素类型
            Type elementType = $Gson$Types.getCollectionElementType(type.getType(), type.getRawType());
            //生成该元素类型的typeAdapter
            TypeAdapter<?> elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType));
            return new CollectionTypeAdapter(elementType,elementTypeAdapter,constructorConstructor.get(type));
        }
        return null;
    }
}
